import React, { useState, useImperativeHandle, useEffect } from 'react';
import { Collapse, Table, Tooltip, Icon, Input } from 'antd';
import { VARIABLE_TYPE } from '../../../../utils/constant';
import { connect } from 'react-redux';
import FormItem from 'src/components/FormItem';

import { compare } from 'src/utils/compare';
const Panel = Collapse.Panel;

function ReturnVariables(props) {
  const { disabled, compareData = [], codes, returnResults, value, isResult, isReturned, fieldClassification } = props;
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [variables, setVariables] = useState(returnResults);
  useImperativeHandle(props.createRef, () => ({
    // 暴露方法给父组件,收集验证值
    getValue: (cb) => {
      const data = isReturned
        ? selectedRowKeys
            .map((it) => {
              const [var_type, code, decision_set_code] = it.split(';');
              const _has = value.find((it) => {
                return (
                  it.code === code &&
                  it.var_type === var_type &&
                  (it.decision_set_code ? it.decision_set_code === decision_set_code : true)
                );
              });
              const _cur = returnResults.find((it) => {
                return (
                  it.code === code &&
                  it.var_type === var_type &&
                  (it.decision_set_code ? it.decision_set_code === decision_set_code : true)
                );
              });
              return _has
                ? _has
                : {
                    var_type: _cur.var_type,
                    code: _cur.code,
                    name: _cur.name,
                    decision_set_code: _cur.decision_set_code,
                    decision_set_name: _cur.decision_set_name,
                  };
            })
            .filter(Boolean)
        : value;
      if (isReturned && !disabled) {
        const inputs = document.querySelectorAll('.output_key');
        const arr = [];
        inputs.forEach((item) => {
          arr.push({
            code: item.getAttribute('data-code'),
            value: item.value,
          });
        });
        data.forEach((item) => {
          arr.forEach((it, i) => {
            if (it.code === item.var_type + ';' + item.code + ';' + item.decision_set_code) {
              item.output_key = it.value;
              arr.splice(i, 1);
              return;
            }
          });
        });
      }
      cb(data);
    },
  }));

  useEffect(() => {
    if (returnResults.length > 0) {
      if (disabled) {
        const data = value
          .map((item) => {
            const cur = returnResults.find(
              (it) =>
                it.code === item.code &&
                it.var_type === item.var_type &&
                (it.decision_set_code ? it.decision_set_code === item.decision_set_code : true),
            );
            if (cur) {
              return {
                ...item,
                compareData: compareData.find(
                  (it) =>
                    item.code === it.code &&
                    item.var_type === it.var_type &&
                    (item.decision_set_code ? it.decision_set_code === item.decision_set_code : true),
                ),
              };
            }
            return null;
          })
          .filter((item) => item);
        // const data = returnResults
        //   .filter((item) => value.find((it) => it.code === item.code && it.var_type === item.var_type && (it.decision_set_code ? it.decision_set_code === item.decision_set_code : true)))
        //   .map((it) => {
        //     return {
        //       ...it,
        //       compareData: compareData.find((item) => item.code === it.code && item.var_type === it.var_type && (it.decision_set_code ? it.decision_set_code === item.decision_set_code : true)),
        //     };
        //   });
        setVariables(data);
      } else {
        const data = returnResults.map((item) => {
          const cur = value.find(
            (it) =>
              it.code === item.code &&
              it.var_type === item.var_type &&
              (it.decision_set_code ? it.decision_set_code === item.decision_set_code : true),
          );
          if (cur) {
            return {
              ...item,
              output_key: cur.output_key,
            };
          }
          return item;
        });
        setVariables(data);
      }
    }
  }, [returnResults]);

  useEffect(() => {
    if (!isReturned && value && value.length > 0) {
      const newValue = value.map((it) => {
        return it.var_type + ';' + it.code + ';' + it.decision_set_code;
      });
      setSelectedRowKeys(newValue);
      return;
    }
    if (value && value.length > 0 && returnResults && returnResults.length > 0) {
      const newValue = value
        .filter((item) =>
          returnResults.find(
            (it) =>
              it.code === item.code &&
              it.var_type === item.var_type &&
              (it.decision_set_code ? it.decision_set_code === item.decision_set_code : true),
          ),
        )
        .map((it) => {
          return it.var_type + ';' + it.code + ';' + it.decision_set_code;
        });
      setSelectedRowKeys(newValue);
    }
  }, [value, returnResults, isReturned]);

  const formItemsInit = (record) => [
    {
      name: 'output_key' + record.key_id,
      options: {
        initialValue: record.output_key || record.code,
        rules: [
          { required: true, message: '请输入映射CODE' },
          { max: 128, message: '最长128个字符' },
          { pattern: /^[^\u4E00-\u9FA5\s]*$/, message: '非中文和空白字符' },
        ],
      },
      component: <Input className='output_key' data-code={record.var_type_code} disabled={disabled} />,
    },
  ];

  const colums = [
    {
      title: '序号',
      key: 'index',
      width: 40,
      align: 'center',
      render: (text, record, index) => {
        return <span>{index + 1}</span>;
      },
    },
    {
      title: '变量名称',
      dataIndex: 'name',
      key: 'name',
      render: (text, record) => {
        return (
          <Tooltip title={text}>
            <span style={compare({ ...props, value: record, compareData: record.compareData }, 'code')}>{text}</span>
          </Tooltip>
        );
      },
    },
    {
      title: '变量CODE',
      dataIndex: 'code',
      key: 'code',
      render: (text, record) => {
        return (
          <Tooltip title={text}>
            <span style={compare({ ...props, value: record, compareData: record.compareData }, 'code')}>{text}</span>
          </Tooltip>
        );
      },
    },
    {
      title: '映射CODE',
      dataIndex: 'output_key',
      key: 'output_key',
      render: (text, record) => {
        if (disabled) {
          return (
            <Input
              className='output_key'
              defaultValue={text || record.code}
              disabled={disabled}
              style={compare({ ...props, value: record, compareData: record.compareData }, 'output_key')}
            />
          );
        } else {
          const formItems = formItemsInit(record);
          return formItems.map((item, index) => {
            return <FormItem {...props} form={props.form} item={item} colNum={1} key={index} />;
          });
        }
      },
    },
    {
      title: '数据类型',
      dataIndex: 'data_type_name',
      key: 'data_type_name',
      render: (text, record) => {
        return (
          <Tooltip title={text}>
            <span style={compare({ ...props, value: record, compareData: record.compareData }, 'code')}>{text}</span>
          </Tooltip>
        );
      },
    },
    isResult
      ? {
          title: '取值',
          dataIndex: 'result',
          key: 'result',
        }
      : false,
  ].filter(Boolean);

  const result = {};

  const FieldClass = (it, classFi) => {
    const value = fieldClassification.find((item) => item.code === it.classification);
    if (classFi[value.code]) {
      classFi[value.code].dataSource.push(it);
    } else {
      classFi[value.code] = { title: value.value, dataSource: [it] };
    }
    return classFi;
  };

  const RuleResultClass = (it, classFi) => {
    const decision_set_code = it.decision_set_code;
    if (classFi[decision_set_code]) {
      classFi[decision_set_code].dataSource.push(it);
    } else {
      classFi[decision_set_code] = { title: `${it.decision_set_name}(${it.decision_set_code})`, dataSource: [it] };
    }
    return classFi;
  };

  variables &&
    variables.forEach((it) => {
      const data = codes.find((item) => item.code === it.var_type);
      if (data) {
        const { code, value } = data;
        it.var_type_code = it.var_type + ';' + it.code + ';' + it.decision_set_code;
        if (code === VARIABLE_TYPE._FIELD && it.classification) {
          // 字段需要再分类
          if (result[code]) {
            result[code].classFi = FieldClass(it, result[code].classFi || {});
            // 如果不存在，则新增一个种类的属性如：{filed:{title:'字段',dataSource:[{...}]}}
          } else {
            result[code] = { title: value, dataSource: [] };
            result[code].classFi = FieldClass(it, {});
          }
        } else if (code === VARIABLE_TYPE._RuleResult) {
          if (result[code]) {
            result[code].classFi = RuleResultClass(it, result[code].classFi || {});
            // 如果不存在，则新增一个种类的属性如：{filed:{title:'字段',dataSource:[{...}]}}
          } else {
            result[code] = { title: value, dataSource: [] };
            result[code].classFi = RuleResultClass(it, {});
          }
        } else {
          // 如果已经存在
          if (result[code]) {
            result[code].dataSource.push(it);
            // 如果不存在，则新增一个种类的属性如：{filed:{title:'字段',dataSource:[{...}]}}
          } else {
            result[code] = { title: value, dataSource: [it] };
          }
        }
      }
    });
  const rowSelection = {
    columnWidth: 30,
    onChange: (selectedRowKeys, selectedRows) => {
      setSelectedRowKeys(selectedRowKeys);
    },
    selectedRowKeys: selectedRowKeys,
  };
  return (
    <div>
      {Object.keys(result).length > 0 && (
        <Collapse
          defaultActiveKey={Object.keys(result)}
          expandIcon={({ isActive }) => (isActive ? <Icon type='minus' /> : <Icon type='plus' />)}
        >
          {Object.keys(result).map((code) => {
            const item = result[code];
            return (
              <Panel header={item.title} key={code}>
                <>
                  {item.dataSource.length > 0 && (
                    <Table
                      rowSelection={disabled ? null : rowSelection}
                      rowKey={'var_type_code'}
                      className='fixed'
                      dataSource={item.dataSource}
                      columns={colums}
                      pagination={false}
                      style={{ marginBottom: 20 }}
                    />
                  )}
                  {item.classFi && (
                    <Collapse
                      defaultActiveKey={Object.keys(item.classFi)}
                      expandIcon={({ isActive }) => (isActive ? <Icon type='minus' /> : <Icon type='plus' />)}
                    >
                      {Object.keys(item.classFi).map((classCode) => {
                        const classItem = item.classFi[classCode];
                        return (
                          <Panel header={classItem.title} key={classCode}>
                            <Table
                              rowSelection={disabled ? null : rowSelection}
                              rowKey={'var_type_code'}
                              className='fixed'
                              dataSource={classItem.dataSource}
                              columns={colums}
                              pagination={false}
                            />
                          </Panel>
                        );
                      })}
                    </Collapse>
                  )}
                </>
              </Panel>
            );
          })}
        </Collapse>
      )}
    </div>
  );
}

function mapStateToProps(state) {
  return {
    fieldClassification: state.code.field_classification || [],
  };
}

export default connect(mapStateToProps)(ReturnVariables);
